<template>
  <div class="HomePageView">
    <div class="page-view">
      <div class="describe">
        <span>{{$t("message.Menu.user")}}</span>
        <p class="r-describe" v-if="accType == '1' || accType == '3'">
          <button class="black-btn" @click="openDialog">
            <i class="el-icon-plus"></i>
            <span>{{$t('message.public.addbtn')}}</span>
          </button>
        </p>
      </div>
      <!-- <div class="Tips">
        <div class="l-tips">
          <i class="el-icon-warning"></i>
          <span>
            已选择
            <span style="color:#EA2B3A">1</span>项
          </span>
          <span style="marginLeft:16px">提示描述...</span>
        </div>
        <p class="clear">清空</p>
      </div>-->
      <div class="tableView">
        <el-table
          ref="multipleTable"
          :data="tableData"
          tooltip-effect="dark"
          style="width: 100%"
          :max-height="tableHeight"
          :header-cell-style="{color:'rgba(144,147,153,1)',fontSize:'16px',textAlign:'left'}"
          :cell-style="{color: 'rgba(96,98,102,1)',backgroundColor:'transparent',fontSize:'14px',textAlign:'left'}"
          :row-style="{color: 'rgba(96,98,102,1)',backgroundColor:'transparent',fontSize:'13px',textAlign:'left'}"
        >
          <el-table-column :label="$t('message.userPageTable.userName')">
            <template slot-scope="scope">{{ scope.row.acc }}</template>
          </el-table-column>
          <el-table-column prop="name" :label="$t('message.userPageTable.name')"></el-table-column>
          <el-table-column prop="email" :label="$t('message.userPageTable.email')"></el-table-column>
          <el-table-column prop="type" :label="$t('message.userPageTable.userType')">
            <template slot-scope="scope">
              <span v-if="scope.row.accType == 1">{{$t('message.userPageTable.admin')}}</span>
              <span v-if="scope.row.accType == 2">{{$t('message.userPageTable.ordinaryUsers')}}</span>
            </template>
          </el-table-column>
          <el-table-column prop="name" :label="$t('message.userPageTable.action')">
            <template slot-scope="scope">
              <div class="table-msg-view" v-if="accType==1&&accType!=scope.row.accType || accType==3">
                <span @click="editUser(scope.row)">{{$t('message.public.edit')}}</span>
                <span class="solid"></span>
                <span @click="deleteUser(scope.row)">{{$t('message.public.delete')}}</span>
              </div>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div class="Pagination-box">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page.sync="tableForm.pageIndex"
          :page-size="tableForm.pageSize"
          :page-sizes="[10, 20, 30]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          background
        ></el-pagination>
      </div>
    </div>
    <el-dialog
      :title="$t('message.userPageTable.userRegistration')"
      :visible.sync="centerDialogVisible"
      width="30%"
      :append-to-body="true"
    >
      <el-form
        :label-position="labelPosition"
        label-width="120px"
        :model="formLabelAlign"
        :rules="rules"
        ref="formLabelAlign"
      >
        <el-form-item :label="$t('message.userPageTable.userName')" prop="acc">
          <el-input v-model="formLabelAlign.acc" size="small"></el-input>
        </el-form-item>
        <el-form-item :label="$t('message.userPageTable.uname')" prop="checkName">
          <el-input v-model="formLabelAlign.name" size="small" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item :label="$t('message.userPageTable.paw')" prop="pass">
          <el-input v-model="formLabelAlign.pwd" size="small" type="password" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item :label="$t('message.userPageTable.confirmPsd')" prop="checkPass">
          <el-input v-model="formLabelAlign.checkPass" size="small" type="password" autocomplete="off"></el-input>
        </el-form-item>

        <el-form-item :label="$t('message.userPageTable.email')" prop="checkEmail">
          <el-input v-model="formLabelAlign.email" size="small"></el-input>
        </el-form-item>

        <el-form-item :label="$t('message.userPageTable.userType')" prop="checkAccType">
          <el-select v-model="formLabelAlign.accType" size="small" style="width:100%" :disabled="accTypeFlag">
            <el-option
              v-for="item in accTypeList"
              :key="item.val"
              :label="item.label"
              :value="item.val"
            ></el-option>
          </el-select>
        </el-form-item>

        <el-form-item :label="$t('message.userPageTable.mobile')">
          <el-input v-model="formLabelAlign.mobile" size="small"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button size="small" @click="centerDialogVisible = false">{{$t('message.public.cancel')}}</el-button>
        <el-button type="primary" size="small" @click="saveData()">{{$t('message.public.confirm')}}</el-button>
      </span>
    </el-dialog>
    <el-dialog
      :title="$t('message.userPageTable.editUser')"
      :visible.sync="centerDialogVisible2"
      width="30%"
      :append-to-body="true"
    >
      <el-form
        :label-position="labelPosition"
        label-width="120px"
        :model="formLabelAlign"
        :rules="rules"
        ref="formLabelAlign"
      >
        <el-form-item :label="$t('message.userPageTable.userName')" prop="acc">
          <el-input v-model="formLabelAlign.acc" size="small" disabled></el-input>
        </el-form-item>
        <el-form-item :label="$t('message.userPageTable.uname')" prop="checkName">
          <el-input v-model="formLabelAlign.name" size="small"></el-input>
        </el-form-item>
        <el-form-item :label="$t('message.userPageTable.paw')" prop="pass">
          <el-input v-model="formLabelAlign.pwd" size="small" type="password" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item :label="$t('message.userPageTable.confirmPsd')" prop="checkPass">
          <el-input v-model="formLabelAlign.checkPass" size="small" type="password" autocomplete="off"></el-input>
        </el-form-item>

        <el-form-item :label="$t('message.userPageTable.email')" prop="checkEmail">
          <el-input v-model="formLabelAlign.email" size="small"></el-input>
        </el-form-item>
        <el-form-item :label="$t('message.userPageTable.userType')" prop="checkAccType">
          <el-select v-model="formLabelAlign.accType" size="small" style="width:100%" :disabled="accTypeFlag">
            <el-option
              v-for="item in accTypeList"
              :key="item.val"
              :label="item.label"
              :value="item.val"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item :label="$t('message.userPageTable.mobile')">
          <el-input v-model="formLabelAlign.mobile" size="small"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button
          size="small"
          @click="centerDialogVisible2 = false"
        >{{$t('message.public.cancel')}}</el-button>
        <el-button type="primary" size="small" @click="saveData()">{{$t('message.public.confirm')}}</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { getUser, delUser, addUser } from "../../api/api";
import { getLocalStorage } from "../../utils/storage";
// 导出模块
export default {
  // 模块名字
  name: "HomePageView",
  // 模块数据
  data() {
    var validatePass = (rule, value, callback) => {
      if (value === "") {
        callback(new Error(this.$t('message.userPageTable.rules.checkPsd')));
      } else {
        if (this.formLabelAlign.pwd !== "") {
          this.$refs.formLabelAlign.validateField("checkPass");
        }
        callback();
      }
    };
    var validatePass2 = (rule, value, callback) => {
      if (value !== this.formLabelAlign.pwd) {
        callback(new Error(this.$t('message.userPageTable.rules.checkPsdTip')));
      } else {
        callback();
      }
    };

    var checkMobile = (rule, value, callback) => {
      if (
        !/^(((\\+\\d{2}-)?0\\d{2,3}-\\d{7,8})|bai((\\+\\d{2}-)?(\\d{2,3}-)?([1][3,4,5,7,8][0-9]\\d{8})))$/.test(
          this.formLabelAlign.mobilex
        )
      ) {
        callback(new Error(this.$t('message.userPageTable.rules.checkMobile')));
      } else {
        callback();
      }
    };

    var checkEmail = (rule, value, callback) => {
      if (
        !/^([A-Za-z0-9_+-.])+@([A-Za-z0-9\-.])+\.([A-Za-z]{2,22})$/.test(
          this.formLabelAlign.email
        )
      ) {
        callback(new Error(this.$t('message.userPageTable.rules.checkEmail')));
      }
    };
    var checkAcc = (rule, value, callback) => {
      if (this.formLabelAlign.acc == "") {
        callback(this.$t('message.userPageTable.rules.checkUserName'));
      }
    };
    var checkName = (rule, value, callback) => {
      if (this.formLabelAlign.name == "") {
        callback(new Error(this.$t('message.userPageTable.rules.checkName')));
      }
    };
    var checkAccType = (rule, value, callback) => {
      if (this.formLabelAlign.accType == "") {
        callback(new Error(this.$t('message.userPageTable.rules.checkUserType')));
      }
    };
    //数据
    return {
      rules: {
        acc: [{ validator: checkAcc, trigger: "blur", required: true }],
        pass: [{ validator: validatePass, trigger: "blur", required: true }],
        checkPass: [
          { validator: validatePass2, trigger: "blur", required: true },
        ],
        checkMobile: [{ validator: checkMobile, trigger: "blur" }],
        checkEmail: [
          { validator: checkEmail, trigger: "blur", required: true },
        ],
        checkName: [{ validator: checkName, trigger: "blur", required: true }],
        checkAccType: [{ validator: checkAccType, trigger: "blur", required: true }]
      },

      accType: getLocalStorage("accType"),
      tableData: [],
      total: 0,
      tableForm: {
        pageIndex: 1,
        pageSize: 10,
        fileID: "",
        userID: getLocalStorage("userID"),
      },
      centerDialogVisible: false,
      centerDialogVisible2: false,
      formLabelAlign: {
        id: "",
        pwd: "",
        name: "",
        sex: "",
        age: 0,
        idNumber: "",
        mobile: "",
        email: "",
        createTime: "",
        creater: getLocalStorage("userID"),
        acc: "",
        accType: "",
        type: "",
        modifyTime: "",
        modifier: getLocalStorage("userID"),
        checkPass: "",
      },
      accTypeList: [
        {
          label: this.$t('message.userPageTable.admin'),
          val: 1,
        },
        {
          label: this.$t('message.userPageTable.ordinaryUsers'),
          val: 2,
        },
      ],
      labelPosition: "right",
      tableHeight: 450,
      accTypeFlag:true
    };
  },
  // 注册组件
  components: {},
  // 监听指定值，只有指定值变化，才会触发
  watch: {},
  // 里面的函数只有调用才会执行（实时计算）里面是定义的方法
  methods: {
    handleSizeChange(val) {
      this.tableForm.pageSize = val;
      getUser(this.tableForm).then((res) => {
        this.tableData = [];
        this.total = 0;
        if (res.data.code != 0) {
          return;
        }
        this.tableData = res.data.data;
        this.total = res.data.count;
      });
    },
    handleCurrentChange(val) {
      this.tableForm.pageIndex = val;
      getUser(this.tableForm).then((res) => {
        this.tableData = [];
        this.total = 0;
        if (res.data.code != 0) {
          return;
        }
        this.tableData = res.data.data;
        this.total = res.data.count;
      });
    },
    getData() {
      getUser(this.tableForm).then((res) => {
        console.log(res);
        this.tableData = [];
        this.total = 0;
        if (res.data.code != 0) {
          return;
        }
        this.tableData = res.data.data;
        this.total = res.data.count;
      });
    },
    deleteUser(row) {
      let data = {
        id: [row.userId],
        UserID: getLocalStorage("userID"),
      };
      this.$confirm(
        this.$t("message.userPageTable.userTips"),
        this.$t("message.public.delete"),
        {
          confirmButtonText: this.$t("message.public.confirm"),
          cancelButtonText: this.$t("message.public.cancel"),
          type: "warning",
        }
      )
        .then(() => {
          delUser(data).then((res) => {
            let totalPage = Math.ceil(
              (this.total - 1) / this.tableForm.pageSize
            );
            let currentPage =
              this.tableForm.pageIndex > totalPage
                ? totalPage
                : this.tableForm.pageIndex;
            this.tableForm.pageIndex =
              this.tableForm.pageIndex < 1 ? 1 : currentPage;
            this.getData();
          });
        })
        .catch(() => {});
    },
    saveData() {
      this.$refs.formLabelAlign.validate((valid) => {
        console.log(valid);
        if (valid) {
          // alert('submit!');
        } else {
          console.log("error submit!!");
          return false;
        }
      });
      addUser(this.formLabelAlign).then((res) => {
        console.log(this.formLabelAlign, res);
        if (res.data.code != 0) {
          this.$message.error(res.data.msg);
          return;
        }
        this.getData();
        this.centerDialogVisible = false;
        this.centerDialogVisible2 = false;
      });
    },
    editUser(row) {
      this.centerDialogVisible2 = true;
      this.formLabelAlign.acc = row.acc;
      this.formLabelAlign.age = row.age;
      this.formLabelAlign.email = row.email;
      this.formLabelAlign.idNumber = row.idNumber;
      this.formLabelAlign.mobile = row.mobile;
      this.formLabelAlign.name = row.name;
      this.formLabelAlign.sex = row.sex;
      this.formLabelAlign.id = row.userId;
      this.formLabelAlign.pwd = row.pwd;
      this.formLabelAlign.checkPass = row.pwd;
      this.formLabelAlign.accType = row.accType;
    },
    openDialog() {
       
      console.log(this.formLabelAlign.acc)
      this.formLabelAlign.acc = "";
      this.formLabelAlign.pwd = "";
      this.formLabelAlign.name = "";
      this.formLabelAlign.sex = "";
      this.formLabelAlign.age = 0;
      this.formLabelAlign.idNumber = "";
      this.formLabelAlign.mobile = "";
      this.formLabelAlign.email = "";
      this.formLabelAlign.createTime = "";
      this.formLabelAlign.checkPass = "";
      this.formLabelAlign.accType = "";
      this.centerDialogVisible = true;
      this.formLabelAlign.creater = getLocalStorage("userID");
     this.$nextTick(function () {
        this.$refs.formLabelAlign.resetFields();
      });
    },
    resetForm(formName) {
      // this.$refs['formLabelAlign'].resetFields();
    },
  },
  // 创建前状态(里面是操作)
  beforeCreate() {},
  // 创建完毕状态(里面是操作)
  created() {
    this.getData();
    let that = this;
    this.$nextTick(function () {
      let heightStyle = $(".page-view").height() - 240;
      that.tableHeight = heightStyle;
    });

    if(getLocalStorage("accType") == 3 || getLocalStorage("accType") == '3'){
      this.accTypeFlag = false
    }else if(getLocalStorage("accType") == 1 || getLocalStorage("accType") == '1'){
      this.accTypeFlag = false
      this.accTypeList.splice(0,1)
    }
  },
  // 挂载前状态(里面是操作)
  beforeMount() {},
  // 挂载结束状态(里面是操作)
  mounted() {
    const that = this;
    this.$nextTick(function () {
      window.onresize = () => {
        return (() => {
          let heightStyle = $(".page-view").height() - 240;
          that.tableHeight = heightStyle;
        })();
      };
    });
  },
  // 更新前状态(里面是操作)
  beforeUpdate() {},
  // 更新完成状态(里面是操作)
  updated() {},
  // 销毁前状态(里面是操作)
  beforeDestroy() {},
  // 销毁完成状态(里面是操作)
  destroyed() {},
};
</script>
<style  lang="scss" scoped>
.HomePageView {
  width: calc(100% - 257px);
  height: 100%;
  .page-view {
    position: relative;
    width: calc(100% - 112px);
    height: calc(100% - 48px);
    margin: 22px 24px 26px 24px;
    background: rgba(255, 255, 255, 1);
    border-radius: 2px;
    padding: 0 32px;
    border: 1px solid #b4b4b4;
    .describe {
      display: flex;
      align-items: center;
      justify-content: space-between;
      font-size: 16px;
      font-weight: 500;
      color: rgba(0, 0, 0, 0.85);
      padding: 34px 0 34px;
      font-weight: bold;
    }
    .black-btn {
      width: 82px;
      height: 32px;
      line-height: 32px;
      text-align: center;
      font-size: 14px;
      color: rgba(255, 255, 255, 1);
      background: #213d49;
      border-radius: 4px;
      font-weight: 500;
      margin: 0 24px;
      span {
        margin: 0 0 0 8px;
      }
    }
    .r-describe {
      display: flex;
      align-items: center;
      .el-icon-upload2,
      .el-icon-download {
        font-size: 24px;
        color: rgba(144, 147, 153, 1);
        margin: 0 8px;
        cursor: pointer;
      }
    }
  }
  ::v-deep .el-table--enable-row-hover .el-table__body tr:hover > td {
    background-color: #fff1f0 !important;
  }
}
.Tips {
  display: flex;
  justify-content: space-between;
  align-items: center;
  width: 100%;
  height: 40px;
  background: rgba(255, 241, 240, 1);
  border: 1px solid rgba(255, 204, 199, 1);
  border-radius: 6px;
  margin-bottom: 24px;
  .l-tips {
    .el-icon-warning {
      color: #bc000f;
      margin: 0 16px;
    }
    span {
      color: rgba(0, 0, 0, 0.65);
    }
  }
  .clear {
    font-size: 14px;
    color: #bc000f;
    margin-right: 16px;
    cursor: pointer;
  }
}
.Pagination-box {
  position: absolute;
  right: 32px;
  bottom: 65px;
  ::v-deep .el-pagination.is-background .btn-next,
  ::v-deep .el-pagination.is-background .btn-prev,
  ::v-deep .el-pagination.is-background .el-pager li {
    background: rgba(255, 255, 255, 1);
    border-radius: 4px;
    color: rgba(0, 0, 0, 0.65);
    font-size: 14px;
    border: 1px solid rgba(217, 217, 217, 1);
  }
  // ::v-deep .el-pagination.is-background .el-pager li {
  //   background:rgba(30,30,30,1);
  //   color:rgba(255,255,255,1);
  // }
  ::v-deep .el-pagination.is-background .el-pager li:not(.disabled).active {
    background: #213d49;
    color: rgba(255, 255, 255, 1);
  }
  ::v-deep .el-pagination.is-background .el-pager li:not(.disabled):hover {
    color: none;
  }
}
.table-msg-view {
  display: flex;
  justify-content: flex-start;
  align-items: center;
  color: rgba(234, 43, 58, 1);
  font-size: 14px;
  span {
    cursor: pointer;
  }
  .solid {
    width: 1px;
    height: 14px;
    margin: 0 8px;
    cursor: none;
    background: rgba(233, 233, 233, 1);
  }
}
::v-deep .el-form-item {
  margin-bottom: 16px;
}
</style>
 